package base.web.filter;

import base.web.tools.WebUtils;
import org.apache.log4j.MDC;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: YeQing
 * Date: 12-7-5
 * Time: 下午2:18
 * To change this template use File | Settings | File Templates.
 */
public class AuthenticationFilter implements Filter{

    protected String sendRedirect = null;

    protected FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.sendRedirect = filterConfig.getInitParameter("SendRedirect");
        if(this.sendRedirect == null || "".equals(this.sendRedirect)) {
            this.sendRedirect = "/miniui/base/login/base_login.jsp";
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String currentURL = request.getRequestURI();
        String targetURL = currentURL;
        String userID = "";
        if(targetURL.indexOf(".do") != -1) {
            if(targetURL.indexOf("/login.do") != -1) {

            }else {
                Cookie userCookie = WebUtils.getCookie(request ,"userID");
                if(userCookie != null) {
                    userID = userCookie.getValue();
                }
                if(userID == null || "".endsWith(userID)) {
                    request.getRequestDispatcher(this.sendRedirect).forward(request, response);
                    return;
                }
            }
        }
        MDC.put("UserId", userID);
        MDC.put("userIP", request.getRemoteAddr());

        //The request to the next filter , if next filter is Null return;
        filterChain.doFilter(request, response);
    }

    public void destroy() {
        this.sendRedirect = null;
        this.filterConfig = null;
    }
}
